package com.ittx.dzt.jinglyun.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.jinglyun.constant.JinglYunApiConstant;
import com.ittx.dzt.jinglyun.handler.AbstractJinglYunByTimeApiHandler;
import com.ittx.dzt.jinglyun.util.CyUtil;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 增量下载订单
 * <p>
 * cy.salesOrder.download.byTimeFrame
 * /open/api/order/listOrderIds 查询发货单ID列表
 * https://jlopen.jinglyun.com/main/doc?docType=2&cateId=10001&docId=20011
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/10/20
 */
@Slf4j
@Service
public class JinglYunSalesOrderDownloadByTimeService extends AbstractJinglYunByTimeApiHandler<TimeFrameDTO> {

	@Autowired
	private JinglYunSalesOrderDownloadByIdService jinglYunSalesOrderDownloadByIdService;

	@Override
	public String getMqTopic() {
		return JinglYunApiConstant.Rocket.JINGLYUN_DOWNLOAD_ORDER_SEARCHLIST_BY_TIME_BATCH_SPLIT_TOPIC;
	}

	@Override
	public String getJinglMethod() {
		return "/open/api/order/listOrderIds";
	}

	@Override
	public String getLocalApiMethod() {
		return open.constant.PlatformApiConstant.InboundInterface.SALESORDER_DOWNLOAD_BY_TIMEFRAME;
	}

	@Override
	public Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//分发数据,异步下载
		Map<String, Boolean> logMap = new HashMap<>();
		// 判断是rds还是sdk
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);
	}

	@Override
	public Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		//探查成功时不返回完整数据,只返回数量
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
	}

	@Override
	public Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		String orderId = platformApiParamDTO.getPlatformIdentifierTag();
		return this.asyncHandlerById(platformApiParamDTO, orderId);
	}

	/**
	 * sdk
	 * 请求平台接口
	 */
	private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
		Map<String, Object> params = new HashMap<>();
		// gmtStart	String	是	查询开始时间，必须为一个过去的时间。		格式: yyyy-MM-dd HH:mm:ss，如2019-05-21 11:49:18
		params.put("gmtStart", localDateTimeToString(timeFrameDTO.getFrom()));
		// gmtEnd	String	是	查询结束时间，必须为一个过去的时间且晚于gmtStart。		格式: yyyy-MM-dd HH:mm:ss格式，如2019-05-21 11:49:18。		开始时间和结束时间间隔最大24小时。
		params.put("gmtEnd", localDateTimeToString(timeFrameDTO.getTo()));
		// status	Array	否	订单状态：1-锁定库存；2-已取消；3-待发货；4-已发货；6-部分发货；不传默认为全部状态
		List<Integer> statusList = CyUtil.getStatusList(platformApiParamDTO, "sale");
		if (CollUtil.isNotEmpty(statusList)) {
			params.put("status", statusList);
		}
		// pageNo	int	否	分页参数。当前页码，默认值：1
		params.put("pageNo", 1);
		// pageSize	int	否	分页参数。每页显示数量，默认值：50，最大值：300
		params.put("pageSize", 300);
		// fetchType	int	否	发货单查询时间范围类型：不传默认值为0 		0-按照发货单变更时间拉取		1-按照发货单创建时间拉取
		params.put("fetchType", 0);
		boolean hasNext = false;
		// 订单数量
		int total = 0;
		do {
			Result<?> result = this.executeApi(platformApiParamDTO, params, platformApiParamDTO.getRequestId());
			if (result.hasError()) {
				return result;
			}
			Map<String, Object> resultMap = (Map<String, Object>) result.getData();
			List saleDataList = MapUtil.get(resultMap, "entry", List.class);
			if (CollUtil.isNotEmpty(saleDataList)) {
				int beforePageNo = MapUtil.getInt(params, "pageNo");
				params.put("pageNo", beforePageNo + 1);
				hasNext = true;
			} else {
				hasNext = false;
			}
			// 探查模式只返回总数
			if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
				total += saleDataList.size();
			} else {
				for (int i = 0; i < saleDataList.size(); i++) {
					String orderId = saleDataList.get(i).toString();
					sendToSplitTopic(platformApiParamDTO, orderId, logMap);
				}
			}
		} while (hasNext);

		if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
			return Result.success().addData(total);
		} else {
			return Result.success(logMap);
		}
	}

	/**
	 * sdk
	 * 根据单号查询单条订单信息-- 多线程执行
	 */
	@Override
	public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String orderId) {
		Result<?> result = jinglYunSalesOrderDownloadByIdService.getOrderById(platformApiParamDTO, orderId);
		if (!result.isSuccess()) {
			return result;
		}
		return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
	}

	/**
	 * 参数校验
	 *
	 * @param platformApiParamDTO 平台请求参数
	 * @param timeFrameDTO        接口请求参数
	 */
	public Result<?> checkParams(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
		if (timeFrameDTO == null || platformApiParamDTO.getStoreConfig() == null ||
				timeFrameDTO.getTo() == null || timeFrameDTO.getFrom() == null) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0004_MSG, platformApiParamDTO.getRequestId(),
					this.getPlatformCode(), getLocalApiMethod(), timeFrameDTO);
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0004, msg));
		}
		return Result.success();
	}


}
